package com.yingjia.yingjiauniversity.utils;

import android.net.Uri;

import java.util.HashMap;
import java.util.Map;

/**
 * <Uri操作工具类>
 *
 * @author: guoxiangxun
 * @date: 16-10-24 下午1:13
 * @version: v1.0
 */
public class UriUtil {

    private UriUtil() {
        throw new AssertionError();
    }

    /**
     * 获取url的相关集合
     *
     * @param url the url
     * @return the query string
     */
    public static Map<String, String> getQueryString(String url) {
        Uri uri = Uri.parse(url);
        return getQueryString(uri);
    }

    /**
     * 获取url的相关集合
     *
     * @param uri the uri
     * @return the query string
     */
    public static Map<String, String> getQueryString(Uri uri) {
        HashMap<String, String> map = new HashMap<String, String>();
        for (String paramName : uri.getQueryParameterNames()) {
            if (paramName != null) {
                String paramValue = uri.getQueryParameter(paramName);
                if (paramValue != null) {
                    map.put(paramName, paramValue);
                }
            }
        }
        return map;
    }

    /**
     * <为url添加参数>
     *
     * @param url   the url
     * @param name  the name
     * @param value the value
     * @return the string
     * @author: guoxiangxun
     * @date: Oct 27, 2016 4:03:18 PM
     * @version: v1.0
     */
    public static String addQueryParameter(String url, String name, String value) {
        Uri uri = Uri.parse(url);
        return addQueryParameter(uri, name, value);
    }

    /**
     * <为url添加参数>
     *
     * @param uri   the uri
     * @param name  the name
     * @param value the value
     * @return the string
     * @author: guoxiangxun
     * @date: Oct 27, 2016 4:03:18 PM
     * @version: v1.0
     */
    public static String addQueryParameter(Uri uri, String name, String value) {
        String url = uri.toString();
        String uriQuery = uri.getQuery();
        if (uriQuery != null) {
            url += "&";
        } else {
            url += "?";
        }
        url += name + "=" + value;

        return url;
    }

    /**
     * 设置url参数
     *
     * @param url   the url
     * @param name  the name
     * @param value the value
     * @return the query parameter
     */
    public static String setQueryParameter(String url, String name, String value) {
        Uri uri = Uri.parse(url);
        return setQueryParameter(uri, name, value);
    }


    /**
     * 设置url参数
     *
     * @param uri   the uri
     * @param name  the name
     * @param value the value
     * @return the query parameter
     */
    public static String setQueryParameter(Uri uri, String name, String value) {
        String queryValue = uri.getQueryParameter(name);
        String url = uri.toString();
        if (StringUtil.isEmpty(queryValue)) {
            return addQueryParameter(uri, name, value);
        } else {
            return url.replace(name + "=" + queryValue, name + "=" + value);
        }
    }

}
